/**
 * 
 */
package com.zx.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import sun.misc.BASE64Encoder;

import com.zx.web.utils.FilePathUtils;

/**
 * 
 * @author hb
 *
 *         2017年8月18日 上午11:06:51
 */
@WebServlet("*.down")
public class DownLoadAction extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String dir = getServletContext().getRealPath("images");
		String path = request.getServletPath();
		if ("/show.down".equals(path)) {
			// 获得images路径
			// 获得dir中所有的文件
			Collection<File> files = FileUtils.listFiles(new File(dir), null,
					true);
			// 获得所有的文件名
			List<String> list = new ArrayList<String>();
			for (File f : files) {
				list.add(f.getName());
			}

			// 转发到list.jsp中
			request.setAttribute("files", list);
			request.getRequestDispatcher("list.jsp").forward(request, response);
		} else if ("/download.down".equals(path)) {
			// 获得文件名
			String fileName = request.getParameter("filename");
			String uuidPath = FilePathUtils.parsePath(fileName);
			// 目标文件
			File targetFile = new File(dir + uuidPath + "/" + fileName);

			/**
			 * 根据文件的类型设置响应消息头,否则采用默认值
			 * 
			 * 判断文件的类型依据根据文件的后缀
			 */
			String mimeType = getServletContext().getMimeType(fileName);

			response.setContentType(mimeType);
			// 获得请求头User-Agent的值,该之中可以用于判断浏览器的类型
			String userAgent = request.getHeader("User-Agent");
			if (userAgent.contains("Firefox")) {
				// 说用客户端使用的Firefox浏览器
				fileName = base64EncodeFileName(fileName);
			} else {
				// 设置为弹出下载对话框的形式
				// firefox默认采用的是base64的编码,其他浏览器采用是unicode编码
				fileName = URLEncoder.encode(fileName, "utf-8");

			}

			response.setHeader("Content-Disposition", "attachment; filename="
					+ fileName);

			// 必须响应给客户端一个字节流
			OutputStream os = response.getOutputStream();
			InputStream is = new FileInputStream(targetFile);

			byte[] buff = new byte[1024];
			int length = -1;
			while ((length = is.read(buff)) != -1) {
				os.write(buff, 0, length);
			}

		}
	}

	// 文件名的进行base64的解码
	public String base64EncodeFileName(String fileName) {
		BASE64Encoder base64Encoder = new BASE64Encoder();
		try {
			return "=?UTF-8?B?"
					+ new String(base64Encoder.encode(fileName
							.getBytes("UTF-8"))) + "?=";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}
